package com.javasm.mingming.socket;

import com.javasm.mingming.common.exception.JavasmException;
import com.javasm.mingming.common.exception.JavasmExceptionEnum;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author javasm
 * @version 0.1
 * @className RoomSocket
 * @descriptioin:
 * @date 2025/1/20 15:20
 * @since jdk11
 */
@Component
@ServerEndpoint("/room/{roomId}/{uid}")
public class RoomSocket {
    Logger logger = LogManager.getLogger(RoomSocket.class);

    //房间人数
    private static AtomicInteger onlinePersons = new AtomicInteger(0);
    //房间人员集合Map<roomId,Set<客户端>>
    private static Map<String, Set<Session>> roomMap = new ConcurrentHashMap<>(8);


    @OnOpen
    public void enterRoom(@PathParam("roomId") String roomId,
                          @PathParam("uid") String uid,
                          Session session) {
        //获取当前房间的session列表
        Set<Session> set = roomMap.get(roomId);
        if (set == null) {
            //线程安全的集合
            set = new CopyOnWriteArraySet<>();
            //当前连接进来的这个人,添加到 房间用户集合里
            set.add(session);
            //set集合,添加到 map中
            roomMap.put(roomId, set);
        } else {
            set.add(session);
        }
        //进入房间成功
        //房间人数+1
        onlinePersons.incrementAndGet();
    }

    @OnClose
    public void close(@PathParam("roomId") String roomId,
                      @PathParam("uid") String uid,
                      Session session) {
        //离开房间
        if (roomMap.containsKey(roomId)) {
            roomMap.get(roomId).remove(session);
        }
        //房间人数-1
        onlinePersons.decrementAndGet();
    }

    @OnError
    public void error(Throwable throwable) {
        throwable.printStackTrace();
        //logger.error(throwable.getMessage());
    }

    @OnMessage
    public void replyMessage(@PathParam("roomId") String roomId,
                             @PathParam("uid") String uid,
                             Session session, String msg) {
        logger.info("接收到用户{}的数据:{}", uid, msg);
        sendMessage(roomId, msg);
    }

    public void sendMessage(String roomId, String message) {
        if (roomMap != null) {
            //获取当前房间,所有人的session信息
            Set<Session> sessions = roomMap.get(roomId);
            if (sessions != null) {
                sessions.forEach(s -> {
                    try {
                        s.getBasicRemote().sendText(message);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        }

    }


}
